import { error, JsonAsset, resources, SpriteFrame } from "cc";

/**
 * 数据管理器
 */
export default class ResourceManager
{
    public static get Instance() : ResourceManager {
        if(!this._Instance)
            this._Instance = new ResourceManager();
        return this._Instance; 
    }
    private static _Instance : ResourceManager;

    private constructor() {
        
    }

    private dataMap : Map<string,SpriteFrame> = new Map();

    /**
     * DataManager 初始化
     */
    public Init(){

    }

    public async GetSprite(key:string,dir) : Promise<SpriteFrame>{
        let data = this.dataMap.get(key);
        if(!data){
            data = await this.loadSprite(key,dir);
            this.dataMap.set(key,data);
            return data;
        }
        return data as SpriteFrame;
    }

    private loadSprite(key : string,dir) : Promise<SpriteFrame>{
        let path = dir + key + "/spriteFrame";
        return new Promise<SpriteFrame>((resolve,reject)=>{
            resources.load(path,SpriteFrame,(error,sprite)=>
                {
                    if(error){
                        reject("ResourceManager: Resource "+key+" Not Found!")
                    }
                    resolve(sprite);
                })
        });
    }

    public TestShowData(){
        console.log(this.dataMap);
    }
}